define('user', ['config', 'jquery', 'cookie'], function(config, $, cookie){
	//获得图片的后缀名
	function getType (fileName){
		var type = fileName.split('\.');
		type = type[type.length -1];
		return type;
	};

	//当图片文件名过长时，截去中间部分，分中英文情况处理
	function handleFile(fileName){
		if (fileName.match(/\\/)){
			var temp = fileName.split(/\\/);
			fileName = temp[temp.length -1];
		}
		var nameLength = 0;
		var type = getType(fileName);
		for (var i = 0; i < fileName.length - type.length -3; i++) {
			var charCode = fileName.charCodeAt(i);
			//字符为非中文
			if (charCode >= 0 && charCode <= 128){
				nameLength += 1;
			}
			else{
				nameLength += 2;
			}
			if (nameLength > 25){
				fileName = fileName.substr(0, i-3) + '....' + 
					fileName.substr(fileName.length -type.length -6, type.length +6);
				break;
			}
		}
		return fileName;
	};

	return {
		quit: function(){
			$('#top_bar .user .quit').on('click', function(){
				cookie.setCookie('userId', '');
				cookie.setCookie('name', '');
				cookie.setCookie('avatarUrl', '');
				cookie.setCookie('gender', '');
				cookie.setCookie('grade', '');
				cookie.setCookie('phone', '');
				cookie.setCookie('province', '');
				cookie.setCookie('city', '');
				cookie.setCookie('school', '');
				window.location.reload();
			});
		},
		changePass: function(){
			$('#changePassModal .main-submit').on('click', function(){
				var userId = cookie.getCookie('userId');
				var oldPassword = $('#oldPassword').val();
				var password1 = $('#changePassword1').val();
				var password2 = $('#changePassword2').val();
				var isTeacher = 0;
				var flag = true;

				if (userId == ''){		//用户已失效，需重新登录
					alert('用户已失效，需重新登录!');
					flag = false;
					window.location.reload();
					return ; 
				}

				if (oldPassword == ''){
					$('#changePassModal .error:eq(0)').html('<span>旧密码不能为空</span>');
					flag = false;
				}
				if (password1 == ''){
					$('#changePassModal .error:eq(1)').html('<span>新密码不能为空</span>');
					flag = false;
				}
				if (password2 == ''){
					$('#changePassModal .error:eq(2)').html('<span>确认密码不能为空</span>');
					flag = false;
				}
				else if (password1 != '' && password1 != password2){
					$('#changePassModal .error:eq(2)').html('<span>两次输入密码不同</span>');
					flag = false;
				}

				if (flag){
					var request = $.ajax({
						url : config['api']['changePass'][0].replace('<user_id>', userId),
						type : config['api']['changePass'][1],
						data : {
							oldPassword : oldPassword,
							newPassword: password1
						},
						dataType : 'json',
						async : true,
						error : function(err){
						console.log(err);
							if (err['status'] == '403'){
								$('#changePassModal .error:eq(0)').html('<span>密码错误，请重新输入</span>');
							}
							else{
								$('#changePassModal .error:eq(2)').html('<span>连接服务器出错！</span>');
							}

							$('#oldPassword').val('');
							$('#changePassword1').val('');
							$('#changePassword2').val('');
							setTimeout(function(){
								$(document).one('click', function(){
									$('#changePassModal .error').html('');
								});
							}, 10);	
						},
						success : function(data){
							alert('修改成功！');
							//跳转到首页
							window.location.reload();
						}
					});
				}
				else{	//信息格式错误，绑定全局点击事件，去除错误提示信息
					setTimeout(function(){
						$(document).one('click', function(){
							$('#changePassModal .error').html('');
						});
					}, 10);
				}
			});
		},
		updateInfo : function(){
			//从cookie拿出用户数据，并填在input框中
			$('#updateName').val(cookie.getCookie('name'));
			$('#updateProvince').val(cookie.getCookie('province'));
			$('#updateCity').val(cookie.getCookie('city'));
			$('#updatePhone').val(cookie.getCookie('phone'));
			$('#updateSchool').val(cookie.getCookie('school'));

			if (cookie.getCookie('grade') != ''){
				$('#updateGrade').val(cookie.getCookie('grade'));
			}
			var gender = cookie.getCookie('gender');
			if (gender != ''){
				if (gender == 1){
					$('input[name="updateGender"]:checked').removeAttr('checked');
					$('input[name="updateGender"]').eq(0).attr('checked', true);
					$('.update-user-info .gender .male img').attr('src', 'image/check2.png');
				}	
				else{
					$('input[name="updateGender"]:checked').removeAttr('checked');
					$('input[name="updateGender"]').eq(1).attr('checked', true);
					$('.update-user-info .gender .female img').attr('src', 'image/check2.png');
				}
			}

			//点击性别按钮
			$('.update-user-info .gender').on('click', '.male', function(){
				$('.update-user-info .gender .female img').attr('src', 'image/check1.png');
				$('input[name="updateGender"]').eq(1).attr('checked', false);
				$('input[name="updateGender"]').eq(0).attr('checked', true);
				$('.update-user-info .gender .male img').attr('src', 'image/check2.png');
			});
			$('.update-user-info .gender').on('click', '.female', function(){
				$('.update-user-info .gender .male img').attr('src', 'image/check1.png');
				$('input[name="updateGender"]').eq(0).attr('checked', false);
				$('input[name="updateGender"]').eq(1).attr('checked', true);
				$('.update-user-info .gender .female img').attr('src', 'image/check2.png');
			});

			//点击修改按钮
			$(document).on('click', '.submit-div img', function(){
				var userId = cookie.getCookie('userId');
				var avatarUrl = cookie.getCookie('avatarUrl');
				var name = $('#updateName').val();
				var gender = $('input[name="updateGender"]:checked').val();
				var grade = $('#updateGrade').val();
				var province = $('#updateProvince').val();
				var city = $('#updateCity').val();
				var phone = $('#updatePhone').val();
				var school = $('#updateSchool').val();

				if (userId == ''){		//用户已失效，需重新登录
					alert('用户已失效，需重新登录!');
					$('#top_bar .user').css('display', 'none');
					$('#top_bar .log_reg').css('display', 'inline');
					return false; 
				}

				//修改数据
				var sendData = {
					avatarUrl: avatarUrl,
					name: name,
					gender: gender,
					grade: grade,
					province: province,
					city: city,
					phone: phone,
					school: school	
				}
				//用户名和手机，若没修改则不返回
				if (name == cookie.getCookie('name')){
					delete sendData.name;
				}
				if (phone == cookie.getCookie('phone')){
					delete sendData.phone;
				}

				//用户选择图片，但没上传
				// if ($('#uploadImg').css("display") != "none" && $('#uploadImg').hasClass('btn-primary')){
				// 	var _confirm = confirm("你的头像还没上传，确定放弃上传吗？");
				// 	if (!_confirm){
				// 		return false;
				// 	}
				// }

				//改变按钮为修改中状态
				$(this).attr('src', 'image/modifying.png');
				var request = $.ajax({
					url : config['api']['updateInfo'][0].replace('<user_id>', userId),
					type : config['api']['updateInfo'][1],
					data : sendData,
					dataType : 'json',
					async : true,
					error : function(err){
						//改变按钮为原状态
						$('.submit-div img').attr('src', 'image/modify.png')
						console.log(err);
						alert('修改失败！用户名或手机已存在');
					},
					success : function(data){
						console.log(data);
						cookie.setCookie('userId', userId);
						cookie.setCookie('avatarUrl', avatarUrl);
						cookie.setCookie('name', name);
						cookie.setCookie('gender', gender);
						cookie.setCookie('grade', grade);
						cookie.setCookie('province', province);
						cookie.setCookie('city', city);
						cookie.setCookie('phone', phone);
						cookie.setCookie('school', school);

						alert('修改成功！');
						//跳转到首页
						window.location.reload();
					}
				});
			});
		},
		updateAvatar: function(){
			var alreadyUpload = false;
			var uploadFileName;
			
			//点击选择图片按钮，与隐藏表单中按钮绑定
			$("#avatar_chooseImg").on("click", function() {
				var $selectFile = $( $("#avatar_hidden_form") ).find("input[type=file]");
				$selectFile.trigger('click');
			});

			//点击上传按钮
			$('#avatar_uploadImg').on('click', function(){
				if (cookie.getCookie('userId') == ''){
					alert('用户已失效，需重新登录!');
					window.location.reload();
					return false;
				}

				var fileName = $('#avatar_hidden_form input[type="file"]').val();
				if (getType(fileName).match(/(bmp|gif|jpg|jpeg|png)/) == null){
					alert('图片格式必须为jpg/jpeg/png/gif/bmp!');
					return false;
				}

				//修改上传按钮为不可选状态
				$('#avatar_uploadImg').addClass('disabled');
				$('#avatar_uploadImg').text('正在上传...');

				//触发表单提交按钮的点击事件
				$('#avatar_hidden_form input[type="submit"]').click();

				//iframe获得服务器返回的url
				$('#avatar_hidden_iframe').on('load', function(){
					var response = $('#avatar_hidden_iframe').contents().find('pre').html();
					//阿里云的图片url地址
					var avatarUrl = JSON.parse(response)['url'];
					console.log(avatarUrl);
					cookie.setCookie('avatarUrl', avatarUrl);

					//修改上传按钮为已上传状态
					$('#avatar_uploadImg').removeClass('btn-primary');
					$('#avatar_uploadImg').addClass('btn-success active');
					$('#avatar_uploadImg').text('已上传');
					alert('上传成功！请按"修改"应用变更')

					alreadyUpload = true;
					uploadFileName = $('.select-button h3').text();
				});
			});

			//监听input type="file"的变化，隐藏或显示上传按钮
			$('#avatar_hidden_form input[type="file"]').on('change', function(){
				var fileName = $(this).val();
				if (fileName != ''){
					fileName = handleFile(fileName);
					$('.select-button h3').text(fileName);

					$('#avatar_uploadImg').text('上传');
					$('#avatar_uploadImg').removeClass('disabled active btn-success');
					$('#avatar_uploadImg').addClass('btn-primary');
					$('#avatar_uploadImg').css("display", "inline");
				}
				else{
					if (alreadyUpload == false){
						$('#avatar_uploadImg').css("display", "none");
						$('.select-button h3').text('支持JPG,PNG格式，请不要超过2M');
					}
					else {
						$('.select-button h3').text(uploadFileName);
						$('#avatar_uploadImg').removeClass('btn-primary');
						$('#avatar_uploadImg').addClass('btn-success disabled active');
						$('#avatar_uploadImg').text('已上传');
					}
				}
			});
		}
	};
});